package cn.jhh.base.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;


import java.util.List;

/**
 * @author hmxchen
 * @version 1.0
 * @description 全局异常
 * @date 2023/1/30 11:05
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
    @ResponseBody
    @ExceptionHandler(CustomException.class)
    public RestErrorResponse doCustomException(Exception e){
        log.error("捕获异常：{}",e.getMessage());
        e.printStackTrace();
        return new RestErrorResponse(e.getMessage());
    }
    /**捕获不可预知异常 Exception*/
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public RestErrorResponse doException(Exception e){
        log.error("捕获异常：{}",e.getMessage());
        e.printStackTrace();
        if(CommonError.UNAUTHORIZED.getErrMessage().equals(e.getMessage())){
            return new RestErrorResponse("没有操作此功能的权限");
        }
        return new RestErrorResponse(CommonError.UNKNOWN_ERROR.getErrMessage());
    }
    /**捕获方法参数异常 Exception*/
    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public RestErrorResponse doMethodArgumentNotValidException(MethodArgumentNotValidException e){

        BindingResult bindingResult = e.getBindingResult();
        //校验的错误信息
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        //收集错误
        StringBuffer errors = new StringBuffer();
        fieldErrors.forEach(error->{
            errors.append(error.getDefaultMessage()).append(",");
        });
        return new RestErrorResponse(errors.toString());
    }

}
